﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Interceptor : MonoBehaviour {

    GameObject Player;
    Rigidbody rb,rb_Player;

    Vector3 Vr,Sr,distance;
    Vector3 target;
    float p,tc;

    public float dx, dz, abs_dx, abs_dz;
    public int flag, a, b;

    public float speed = 30.0f;

    // Use this for initialization
    void Start () {
        Player = GameObject.Find("Player");
        rb = GetComponent<Rigidbody>();
        rb_Player = Player.GetComponent<Rigidbody>();
    }
    // Update is called once per frame
    void Update () {
        //速度差
        Vr = rb_Player.velocity - rb.velocity;

        if (Vr.magnitude > 1)
        {
            //位移差
            Sr = new Vector3(Player.transform.position.x - rb.position.x, 0, Player.transform.position.z - rb.position.z);
            //靠拢时间
            tc = Vr.magnitude / Sr.magnitude;
            target = rb_Player.transform.position + (rb_Player.velocity * tc);

            dx = target.x - rb.transform.position.x;
            dz = target.z - rb.transform.position.z;
            //取绝对值
            abs_dx = System.Math.Abs(dx);
            abs_dz = System.Math.Abs(dz);
            a = dx > 0 ? 1 : -1;
            b = dz > 0 ? 1 : -1;
            flag = 0;
            if (abs_dz >= abs_dx)
            //z轴上距离大于x轴
            {
                //将两值交换 使大值存储在 abs_dx 中
                float cur;
                cur = abs_dx;
                abs_dx = abs_dz;
                abs_dz = cur;
                flag = 1;//向z轴方向
            }
            p = 2 * abs_dz - abs_dx;
            distance = Vector3.zero;
            if (p >= 0)
            {
                if (flag == 0)
                    distance = Vector3.forward * b;
                else
                    distance = Vector3.right * a;
            }
            if (flag == 0)
                distance += Vector3.right * a;
            else
                distance += Vector3.forward * b;

        }
        else
            distance = Player.transform.position - rb.position;

        rb.AddForce(distance.normalized * speed);

        //distance = new Vector3(target.x - rb.position.x, target.y - rb.position.y, target.z - rb.position.z).normalized;
        //rb.AddForce(distance * speed);
    }
}
